<template>
  <div>
    <div>
      <el-table-form ref="form" :model="query">
        <el-form-item class="merge-item">
          <el-select v-model="type" style="width: 170px; margin-right: 2px;">
            <el-option label="投保单号" value="insureCode" />
            <el-option label="客户编号" value="csmCode" />
            <el-option label="客户名称" value="csmName" />
            <el-option label="备注" value="remark" />
          </el-select>
          <el-input v-model="txt" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="客户类型:" prop="csmType">
          <el-select v-model="query.csmType" filterable clearable placeholder="请选择">
            <el-option
              v-for="item in csmTypeMap"
              :key="item.value"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态:">
          <el-select v-model="query.insureStatus" filterable clearable placeholder="请选择">
            <el-option
              v-for="item in insureStatusMap"
              :key="item.value"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属机构:">
          <el-tree-select
            v-model="query.ckOrgSNNo"
            clearable
            class="tree-select"
            :popover-width="360"
            :select-params="{
              clearable: true,
              placeholder: '请选择',
              loading: $loadingPlugin.getTreeData
            }"
            :tree-params=" {
              'default-expand-all': true,
              'expand-on-click-node': false,
              'highlight-current': true,
              props:{
                value:'orgSNNo',
                label: 'orgName',
                disabled: 'disabled',
              },
              data: treeData
            }"
          />
        </el-form-item>
        <el-form-item :table-form-merge="2" class="merge-item">
          <el-select v-model="dateType" style="width: 170px; margin-right: 2px;">
            <el-option label="创建日期" value="createTime" />
            <el-option label="变更日期" value="updateTime" />
            <el-option label="审核日期" value="auditDt" />
          </el-select>
          <el-date-picker
            v-model="date"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <template v-slot:btns>
          <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
        </template>
      </el-table-form>
    </div>
    <div style="margin-bottom: 10px;" class="btn-group">
      <div>
        <el-button type="primary" icon="el-icon-plus" @click="add">新增</el-button>
        <el-button type="primary" icon="el-icon-export" @click="exportPolicy">导出</el-button>
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{bottomOffset:10}"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <add ref="add" />
    <flow-info ref="infoCircul" />
  </div>
</template>
<script>
  import { queryInsureOrderManageList, queryInsureListExport, auditIssureOrder, revertCheckIssureOrder, deleteIssureOrder } from '@/api'
  import { formatColumnMap, parseTime } from '@/utils'
  import moment from 'dayjs'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import Add from './Add'
  import FlowInfo from '../../../components/FlowInfoCommon'

  export default {
    name: 'tabsOne',
    components: {
      Add, FlowInfo
    },
    props: {
      csmTypeMap: {
        type: Array,
        required: true
      },
      insureStatusMap: {
        type: Array,
        required: true
      }
    },
    data() {
      return {
        actionColWidth: 80,
        treeData: [],
        type: 'insureCode',
        txt: '',
        dateType: 'createTime',
        date: [moment().startOf('month'), moment()],
        query: {
          csmType: '',
          insureStatus: '',
          ckOrgSNNo: ''
        },
        tableData: {
          total: 0,
          data: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList', 'corpSettingData', 'exportDomain'
      ]),
      column: function() {
        return [
          {
            prop: 'insureCode',
            label: '投保单号',
            width: 110
          },
          {
            prop: 'csmCode',
            label: '客户编号',
            width: 110
          },
          {
            prop: 'csmName',
            label: '客户名称'
          },
          {
            prop: 'csmType',
            label: '客户类型',
            render: (h, { row }) => <span>{ row.csmType && formatColumnMap(this.csmTypeMap, 'value', row.csmType, 'desc') }</span>
          },
          {
            prop: 'csmRgPhone',
            label: '联系电话',
            width: 120
          },
          {
            prop: 'csmAddress',
            label: '客户地址',
            width: 120
          },
          {
            prop: 'ckOrgName',
            label: '所属机构',
            width: 150
          },
          {
            prop: 'insureAcc',
            align: 'right',
            label: '投保金额',
            render: (h, { row }) => <span>{ row.insureAcc ? (row.insureAcc * 1).toFixed(2) : '' }</span>
          },
          {
            prop: 'insureStartDt',
            label: '投保开始时间',
            width: 120,
            render: (h, { row }) => <span>{ row.insureStartDt && parseTime(row.insureStartDt, '{y}-{m}-{d}') }</span>
          },
          {
            prop: 'insureEndDt',
            label: '投保结束时间',
            width: 120,
            render: (h, { row }) => <span>{ row.insureEndDt && parseTime(row.insureEndDt, '{y}-{m}-{d}') }</span>
          },
          {
            prop: 'createTime',
            label: '创建时间',
            width: 180,
            render: (h, { row }) => <span>{ row.createTime && parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'salePersonName',
            label: '售保员',
            width: 110
          },
          {
            prop: 'insureStatus',
            label: '状态',
            render: (h, { row }) => <span style={row.insureStatus === -1 ? 'color: #F56C6C;' : null}>{ row.insureStatus && formatColumnMap(this.insureStatusMap, 'value', row.insureStatus, 'desc') }</span>
          },
          {
            prop: 'auditor',
            label: '审核人',
            width: 110
          },
          {
            prop: 'auditDt',
            label: '审核时间',
            width: 180,
            render: (h, { row }) => <span>{ row.auditDt && parseTime(row.auditDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'modifyTime',
            label: '变更时间',
            width: 180,
            render: (h, { row }) => <span>{row.modifyTime && parseTime(row.modifyTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'remark',
            label: '备注',
            width: 110
          },
          {
            label: '操作',
            fixed: 'right',
            className: 'action-col',
            width: this.actionColWidth,
            render: (h, { row, $index }) => {
              return (
                <div>
                  {row.insureStatus === 1 && <el-link underline={false} size='mini' onClick={() => this.update(row, $index)}>
                    编辑
                  </el-link>}
                  {row.insureStatus === 1 && <el-link underline={false} size='mini' onClick={() => this.audit(row)}>
                    审核
                  </el-link>}
                  {row.insureStatus === 2 && <el-link underline={false} size='mini' onClick={() => this.revertCheck(row)}>
                    反审核
                  </el-link>}
                  <el-link underline={false} size='mini' onClick={() => this.turnRow(row, $index)}>
                    流转信息
                  </el-link>
                  {row.insureStatus === 1 && <el-link underline={false} size='mini' type='danger' onClick={() => this.del(row, $index)}>
                    作废
                  </el-link>}
                </div>
              )
            }
          }
        ]
      }
    },
    async created() {
      await Promise.all([this.getTreeData()])
    },
    methods: {
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        query[this.type] = this.txt
        query[this.dateType] = this.date
        if (this.date && this.date.length === 2) {
          query[this.dateType] = moment(this.date[0]).format()
          query[`${this.dateType}End`] = moment(this.date[1]).format()
        }
        const diff = moment(this.date[1]).diff(moment(this.date[0]), 'days')
        if (diff > 366 * 2) {
          this.$message.warning('保单管理最大支持查询2年')
          return
        }
        const res = await queryInsureOrderManageList(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      // 新增
      async add() {
        await this.$refs.add.open()
        this.search()
      },
      async update(row) {
        await this.$refs.add.open(row)
        this.search()
      },
      // 信息流转
      turnRow(row) {
        this.$refs.infoCircul.open(row.insureCode, 512)
      },
      // 审核
      audit(row) {
        this.$confirm('确认要审核该保险单吗？', '提示', {
          type: 'warning'
        }).then(() => {
          const loading = this.$message({
            message: '正在审核',
            duration: 0,
            iconClass: 'el-icon-loading'
          })
          auditIssureOrder({
            insureCode: row.insureCode,
            csmId: row.csmId,
            csmAddressId: row.csmAddressId
          }).then(() => {
            this.$refs.lbTable.fetch()
            this.$notify({
              title: '提示',
              message: '操作成功',
              type: 'success',
              duration: 2000
            })
          }).finally(() => {
            loading.close()
          })
        })
      },
      // 反审核
      async revertCheck(row) {
        this.$confirm('确认要反审核该保险单吗？', '提示', {
          type: 'warning'
        }).then(() => {
          const loading = this.$message({
            message: '正在反审核',
            duration: 0,
            iconClass: 'el-icon-loading'
          })
          revertCheckIssureOrder({
            insureCode: row.insureCode,
            csmId: row.csmId,
            csmAddressId: row.csmAddressId
          }).then(() => {
            this.$refs.lbTable.fetch()
            this.$notify({
              title: '提示',
              message: '操作成功',
              type: 'success',
              duration: 2000
            })
          }).finally(() => {
            loading.close()
          })
        })
      },
      // 作废
      del(row) {
        this.$confirm('确认要作废该保险单吗？', '提示', {
          type: 'warning'
        }).then(() => {
          const loading = this.$message({
            message: '正在作废',
            duration: 0,
            iconClass: 'el-icon-loading'
          })
          deleteIssureOrder({
            insureCode: row.insureCode,
            csmId: row.csmId,
            csmAddressId: row.csmAddressId
          }).then(() => {
            this.$refs.lbTable.fetch()
            this.$notify({
              title: '提示',
              message: '操作成功',
              type: 'success',
              duration: 2000
            })
          }).finally(() => {
            loading.close()
          })
        })
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 导出
      exportPolicy() {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'info'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.column))
          copyColumn.pop()
          const str = {}
          copyColumn.forEach(item => {
            str[item.prop] = item.label
          })
          queryInsureListExport({
            paramInfo: _this._getQuery(_this.query),
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach(it => {
                width += (it.offsetWidth + 10)
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      }
    }
  }
</script>

